﻿using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Routing;

namespace MingYuanyun.WebApi.Abstractions
{
    public class ApiVersionRoutePrefixConvention : IApplicationModelConvention
    {
        private readonly AttributeRouteModel _apiVersionRoutePrefix;

        public ApiVersionRoutePrefixConvention(IRouteTemplateProvider routeTemplateProvider)
        {
            this._apiVersionRoutePrefix = new AttributeRouteModel(routeTemplateProvider);
        }

        public void Apply(ApplicationModel application)
        {
            foreach (var controller in application.Controllers)
            {
                foreach (var selector in controller.Selectors)
                {
                    if (selector.AttributeRouteModel != null)
                    {
                        selector.AttributeRouteModel =
                            AttributeRouteModel.CombineAttributeRouteModel(_apiVersionRoutePrefix, selector.AttributeRouteModel);
                    }
                    else
                    {
                        selector.AttributeRouteModel = _apiVersionRoutePrefix;
                    }
                }
            }
        }
    }
}
